package com.tywj.panda.driver.task

import android.content.Intent
import android.os.Bundle
import androidx.collection.ArrayMap
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.tywj.lib.net.retrofit.request.BaseRequest
import com.tywj.lib.route.RouteParam
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.view.dialog.showByCZConfig
import com.tywj.panda.customer.common.view.paging.BasePagingFragmentSearch
import com.tywj.panda.driver.R
import com.tywj.panda.driver.api.DriverApi
import com.tywj.panda.driver.entity.DriverTaskEntity
import com.tywj.panda.driver.event.DriverEvent
import com.tywj.panda.driver.route.DriverRoute
import com.tywj.panda.driver.service.GPSLocationService


/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/06/20
 *     desc   : 我的
 *     version: 1.0.0
 * </pre>
 */
@Route(path = DriverRoute.DRIVER_TASK)
class DriverTaskFragment :
    BasePagingFragmentSearch<DriverTaskEntity, DriverTaskEntity.DataBean>(DriverTaskEntity.DataBean::class.java) {

    companion object {
        const val PARAMS_TASK_TYPE = "type"
    }

    private var taskType = ""

    //当前时间
    private var currentTime = ""

    //开始打卡或结束打卡状态
    private var workStatus = 1

    private var gpsService: GPSLocationService? = null

    override fun getRecyclerViewAdapter(): BaseQuickAdapter<DriverTaskEntity.DataBean, *> {
        return DriverTaskAdapter()
    }

    override fun getRequest(): BaseRequest<*> = DriverApi.getTaskList()

    override fun getRequestParams(): ArrayMap<String, String> {
        return DriverApi.listTaskParams(taskStatus = taskType, selectedTime = currentTime)
    }

    //说明，由于服务器不能把返回的时间放到返回的数据最外层，交给前端来处理，在上拉更多时需要把返回的最后一条数据的时间交给服务器。
    override fun getRequestParamsLoadMore(): ArrayMap<String, String> {
        return DriverApi.listTaskParams(
            taskStatus = taskType,
            selectedTime = currentTime,
            time = mAdapter.data.last().createTime
        )
    }

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        taskType = RouteParam(this).getString(PARAMS_TASK_TYPE)

        gpsService = GPSLocationService()
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        with(mStatusLayout) {
            setEmptyLayoutIcon(R.drawable.common_data_is_empty)
            if (taskType == "0") {
                setEmptyLayoutTitle(R.string.driver_today_not_task)
            } else {
                setEmptyLayoutTitle(R.string.driver_today_had_task)
            }
        }
    }

    override fun initListener() {
        super.initListener()


        DriverEvent.loadTaskByCurrentDateEvent.observe(this, Observer {
            currentTime = it
            mPagingHelper.refresh()
        })

        DriverEvent.refreshTaskEvent.observe(this, Observer {
//            shortToast("Event")
            mPagingHelper.refresh()

            if (workStatus == 2) {
                val intent = Intent(requireContext(), GPSLocationService::class.java)
                intent.putExtra(GPSLocationService.PARAMS_BEAN, "")
                intent.putExtra(GPSLocationService.PARAMS_WORK_StATUS, workStatus)
                requireContext().stopService(intent)
            }
        })

        mAdapter.setOnItemClickListener { _, _, position ->
            val bean = mAdapter.data[position]
            // 跳转至班次详情页
            DriverRoute.toBusDetails(bean).navigation(this)
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->

            val bean = mAdapter.data[position]
            when (view.id) {
                //打卡状态
                R.id.tvClockStatus -> {
                    PermissionTool.location {
                        showPunchDialog(bean)
                    }
                }
            }
        }

        gpsService?.setRefreshEvent(object : GPSLocationService.IRefresh {
            override fun refresh() {
                shortToast("refhresh 回调刷新")
                mPagingHelper.refresh()
            }
        })

    }

    private fun showPunchDialog(bean: DriverTaskEntity.DataBean) {
        MaterialDialog(requireContext())
            .title(R.string.common_prompt_title)

            .message(
                if (isStartAction(bean)) {
                    R.string.driver_start_clock_tips
                } else {
                    R.string.driver_end_clock_tips
                }
            )

            .negativeButton(R.string.common_negative)
            .positiveButton(R.string.common_positive) {
                //打卡
                PermissionTool.location {
                    workStatus = if (isStartAction(bean)) {
                        //开始打卡
                        1
                    } else {
                        //结束打卡
                        2
                    }
                    val intent = Intent(requireContext(), GPSLocationService::class.java)
                    intent.putExtra(GPSLocationService.PARAMS_BEAN, bean)
                    intent.putExtra(GPSLocationService.PARAMS_WORK_StATUS, workStatus)
                    requireContext().startService(intent)
                }

            }
            .showByCZConfig()
    }

    //是否是开始打卡
    private fun isStartAction(bean: DriverTaskEntity.DataBean): Boolean {
        return bean.startPunch == 0 && bean.endPunch == 0
    }
}